﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using ArtMath.Component;
using ArtMath.Window.Interface;
using ArtMath.Setting;
using ArtMath.Resource;
using ArtMath.Control;
using ArtMath.Component.Annotation;
using ArtMath.Component.CoordinateSystem;
using ArtMath.Component.Polygon;
using ArtMath.Component.Line;
using ArtMath.Component.Circle;
using ArtMath.Component.Manager;
using ArtMath.Component.Vector;
using ArtMath.Component.ConicalSection;
using ArtMath.Interaction.Interface;
using ArtMath.CommonType;

namespace ArtMath.Window
{
    public partial class ToolsWindow : DockContent, ISwitchLanguage, IObjectCreationArguments
    {
        public class InitializationData
        {
            public ImageList ToolListLargeIcon, ToolListSmallIcon;
            public List<ToolItem> ToolItems = new List<ToolItem>();
            public List<ListViewGroup> ToolGroups = new List<ListViewGroup>();
        }
        public class ToolItem : ListViewItem
        {
            ToolTypeName toolType;
            public ToolTypeName ToolType
            {
                get { return toolType; }
                set
                {
                    toolType = value;
                    switch (toolType)
                    {
                        case ToolTypeName.yxbjy:
                        case ToolTypeName.zdbx:
                        case ToolTypeName.tp:
                        case ToolTypeName.dbfd:
                        case ToolTypeName.yssx:
                        case ToolTypeName.jndfx:
                        case ToolTypeName.bjyxjsx:
                        case ToolTypeName.xggx:
                        case ToolTypeName.ysj:
                        case ToolTypeName.yzb:
                        case ToolTypeName.ygb:
                        case ToolTypeName.dxp:
                        case ToolTypeName.qyxp:
                        case ToolTypeName.lzxdj:
                        case ToolTypeName.yszx:
                        case ToolTypeName.dhs:
                            OptionPanelHeight = 36;
                            break;
                        case ToolTypeName.zbd:
                        case ToolTypeName.csfc:
                        case ToolTypeName.yxysxd:
                        case ToolTypeName.ysxl:
                        case ToolTypeName.yspwx:
                            OptionPanelHeight = 62;
                            break;
                        case ToolTypeName.wb:
                        case ToolTypeName.ysty:
                        case ToolTypeName.yssqx:
                            OptionPanelHeight = 100;
                            break;
                    }
                }
            }
            public int LastOrderIndex { get; set; }
            public int OptionPanelHeight { get; set; }
            public double WindowWidth { get; set; } = 260;
            public ToolItem(ListViewGroup group, string imgKey, ToolTypeName type) : base(string.Empty, imgKey, group)
            {
                ToolType = type;
            }
        }
        [DllImport("user32")]
        static extern bool GetCaretPos(out Point lpPoint);
        Color selectedColor = Color.Red;
        public bool OpenFunctionInputWindow = true;
        [Browsable(false)]
        public SketchPad LinkedPad { get; private set; }
        public void SketchPad_Activated(SketchPad sender)
        {
            LinkedPad = sender;
            if (LinkedPad == null)
            {
                //lvTools.Enabled = toolStrip6.Enabled = false;
                Enabled = false;
            }
            else
            {
                if (LinkedPad.SelectedToolType == ToolTypeName.zz)
                {
                    foreach (ListViewItem item in lvTools.SelectedItems)
                    {
                        item.Selected = false;
                    }
                }
                else
                {
                    OpenFunctionInputWindow = false;
                    foreach (ToolItem item in lvTools.Items)
                    {
                        if (item.ToolType == LinkedPad.SelectedToolType)
                        {
                            item.Selected = true;
                            break;
                        }
                    }
                    OpenFunctionInputWindow = true;
                }
                UIAdaptCoordinate();
                //lvTools.Enabled = toolStrip6.Enabled = true;
                Enabled = true;
            }
        }
        #region Parameters
        [Browsable(false)]
        public string DirectedConstrainedLineSegmentLength
        {
            get { return cbLength.Checked ? tbLen.Text : null; }
        }
        [Browsable(false)]
        public string DirectedConstrainedLineSegmentDirectedAngle
        {
            get { return cbAngle.Checked ? tbAngle.Text : null; }
        }
        [Browsable(false)]
        public string PointSlopeStraightLineSlope
        {
            get { return cbInfinity.Checked ? double.PositiveInfinity.ToString() : tbSlope.Text; }
        }
        [Browsable(false)]
        public string CommonValue
        {
            get { return tbValue.Text; }
        }
        [Browsable(false)]
        public Color HighlighterColor
        {
            get { return selectedColor; }
        }
        [Browsable(false)]
        public Color BallpenColor
        {
            get { return selectedColor; }
        }
        [Browsable(false)]
        public int OrderIndex
        {
            get { return tscbOrder.SelectedIndex; }
        }
        [Browsable(false)]
        public string TextAreaText
        {
            get { return tbText.Text; }
        }
        #endregion
        public ToolsWindow(InitializationData initData)
        {
            InitializeComponent();
            lvTools.LargeImageList = initData.ToolListLargeIcon;
            lvTools.SmallImageList = initData.ToolListSmallIcon;
            ChangeColorTheme(Settings.Instance.ColorTheme);
            lvTools.Groups.AddRange(initData.ToolGroups.ToArray());
            lvTools.Items.AddRange(initData.ToolItems.ToArray());
            CustomSwitchLanguage();
            plCoPoint.Dock = plConstrainedLineSegment.Dock = plValue.Dock = plText.Dock = plBrush.Dock = plRubber.Dock =
                plArrivalAngle.Dock = plSlope.Dock = plDerivedFunction.Dock = plEllipseHyperbola.Dock = plConstrainedVector.Dock =
                plParabola.Dock = DockStyle.Fill;
            Label[] lbls = new Label[] { lblRed, lblOrange, lblYellow, lblGreen, lblBlue, lblIngdigo, lblPurple };
            foreach (Label item in lbls)
            {
                item.Click += (object sender, EventArgs e) =>
                {
                    selectedColor = (sender as System.Windows.Forms.Control).BackColor;
                    setBorder(sender as Label);
                };
            }
        }
        public void ChangeColorTheme(UIColorTheme theme)
        {
            switch (theme)
            {
                case UIColorTheme.Light:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1);
                    break;
                case UIColorTheme.Blue:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1);
                    break;
                case UIColorTheme.Dark:
                    EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1);
                    lvTools.BackColor = Color.FromArgb(37, 37, 38);
                    lvTools.ForeColor = Color.FromArgb(241, 241, 241);
                    break;
            }
        }
        void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme)
        {
            visualStudioToolStripExtender1.SetStyle(toolStrip1, version, theme);
            visualStudioToolStripExtender1.SetStyle(toolStrip6, version, theme);
            visualStudioToolStripExtender1.SetStyle(cmsItem, version, theme);
            visualStudioToolStripExtender1.SetStyle(cmsList, version, theme);
        }
        public void CustomSwitchLanguage()
        {
            string[] headers = new string[] { Resources.Translate("Points"), Resources.JoinLocalizedString("Constructed", "Points"),
                Resources.Translate("Functions"), Resources.JoinLocalizedString("Constructed", "Functions"),
                Resources.Translate("Lines"), Resources.JoinLocalizedString("Constructed", "Lines"), Resources.Translate("Angles"),
                Resources.Translate("Vectors"), Resources.JoinLocalizedString("Constructed", "Vectors"), Resources.Translate("Polygons"),
                Resources.Translate("Circles_Arcs_Sectors"), Resources.JoinLocalizedString("Constructed", "Circles"),
                Resources.Translate("Conics"), Resources.Translate("Customs"), Resources.Translate("Calculations")
            };
            for (int i = 0; i < lvTools.Groups.Count; i++)
            {
                lvTools.Groups[i].Header = headers[i];
            }
            string[] itemTexts = new string[] 
            {
                //点
                Resources.Translate("FreePoint"), Resources.Translate("CoordinatePoint"),
                //构造点
                Resources.Translate("MidPoint"), Resources.Translate("DefiniteProportionateInsertedPoint"),
                Resources.Translate("CrossoverPoint"), Resources.JoinLocalizedString("Shape", "Center"),
                Resources.JoinLocalizedString("Polygon", "BaryCenter"),
                Resources.JoinLocalizedString("Triangle", "CircumCenter"),
                Resources.JoinLocalizedString("Triangle", "InCenter"),
                Resources.JoinLocalizedString("Triangle", "OrthoCenter"),
                //函数
                Resources.Translate(nameof(Function)), Resources.Translate(nameof(ParametricEquation)),
                //构造函数
                Resources.Translate("DerivedFunction"),
                //线
                Resources.Translate(nameof(TwoPointsLineSegment)), Resources.JoinLocalizedString("Directed", "Constrained", "LineSegment"),
                Resources.Translate(nameof(TwoPointsRay)), Resources.JoinLocalizedString("Constrained", "Ray"),
                Resources.Translate(nameof(TwoPointsStraightLine)), Resources.JoinLocalizedString("Constrained", "StraightLine"),
                //构造线
                Resources.Translate(nameof(ParallelLine)), Resources.Translate(nameof(VerticalLine)),
                Resources.Translate(nameof(PerpendicularBisector)), Resources.Translate(nameof(VerticalLineSegment)),
                Resources.Translate(nameof(TangentLine)),
                Resources.Translate(nameof(AngleBisector)), Resources.Translate("AngleNDivider"),
                //角
                Resources.JoinLocalizedString("Constrained", "Angles"),
                //向量
                Resources.Translate(nameof(TwoPointsVector)), Resources.JoinLocalizedString("Constrained", "Vector"),
                //构造向量
                Resources.Translate(nameof(TwoVectorsAddition)),
                Resources.Translate(nameof(TwoVectorsSubtraction)), Resources.Translate(nameof(ParallelVector)),
                Resources.Translate(nameof(VerticalVector)),
                //多边形
                Resources.Translate(nameof(ArbitraryPolygon)),
                Resources.Translate(nameof(RightTriangle)), Resources.Translate(nameof(IsoscelesTriangle)),
                Resources.Translate(nameof(IsoscelesRightTriangle)), Resources.Translate(nameof(EquilateralTriangle)),
                Resources.Translate(nameof(Parallelogram)), Resources.Translate(nameof(Component.Polygon.Rectangle)),
                Resources.Translate(nameof(Diamond)), Resources.Translate(nameof(Square)), Resources.Translate(nameof(Trapezoid)),
                Resources.Translate(nameof(IsoscelesTrapezoid)), Resources.Translate(nameof(RightAngledTrapezoid)),
                Resources.Translate(nameof(RegularPolygon)),
                //圆（弧）、扇形
                Resources.Translate(nameof(CenterPointCircle)),
                Resources.JoinLocalizedString("Constrained", "Circle"), Resources.Translate(nameof(DiameterCircle)),
                Resources.Translate(nameof(ThreePointsCircle)), Resources.Translate(nameof(ThreePointsArc)),
                Resources.Translate(nameof(ThreePointsSector)), Resources.Translate(nameof(RadiusCentralAngleSector)),
                Resources.Translate(nameof(ThreePointsArch)), Resources.Translate(nameof(ChordHeightArch)),
                //构造圆
                Resources.Translate(nameof(CurvatureCircle)), Resources.Translate(nameof(CircumCircle)), Resources.Translate(nameof(InscribedCircle)),
                //圆锥曲线
                Resources.Translate(nameof(LongShortAxisEllipse)), Resources.Translate(nameof(FocusPointEllipse)),
                Resources.Translate(nameof(FocusDirectrixEllipse)), Resources.JoinLocalizedString("Constrained", "Ellipse"),
                Resources.Translate(nameof(RealImaginaryAxisHyperbola)),
                Resources.Translate(nameof(FocusPointHyperbola)), Resources.Translate(nameof(FocusImaginaryAxisHyperbola)),
                Resources.Translate(nameof(FocusDirectrixHyperbola)), Resources.JoinLocalizedString("Constrained", "Hyperbola"),
                Resources.Translate(nameof(FocusDirectrixParabola)), Resources.JoinLocalizedString("Constrained", "Parabola"),
                //自定义
                Resources.Translate(nameof(Ballpen)), Resources.Translate(nameof(Highlighter)), Resources.Translate("Eraser"),
                Resources.Translate("Text"), Resources.Translate(nameof(Picture)),
                //计算
                Resources.Translate("TwoPointsDistance"),
                Resources.Translate("PointStraightLineDistance"), Resources.Translate("TwoParallelLinesDistance"),
                Resources.Translate("TwoStraightLinesIncludedAngle"), Resources.Translate("TwoStraightLinesArrivalAngle"),
                Resources.Translate("ThreePointsAngle"),
                Resources.Translate("TwoVectorsScalarProduct"), Resources.Translate("TwoVectorsCrossProduct"),
            };
            for (int i = 0; i < lvTools.Items.Count; i++)
            {
                lvTools.Items[i].Text = itemTexts[i];
            }
        }
        public ListViewX ToolList
        {
            get { return lvTools; }
        }

        public string EllipseLongAxisHalfLength
        {
            get { return tbA.Text; }
        }

        public string EllipseShortAxisHalfLength
        {
            get { return tbB.Text; }
        }

        public string EllipseFocusAngle
        {
            get { return tbDirAngle1.Text; }
        }

        public string HyperbolaRealAxisHalfLength
        {
            get { return tbA.Text; }
        }

        public string HyperbolaImaginaryAxisHalfLength
        {
            get { return tbB.Text; }
        }

        public string HyperbolaFocusAngle
        {
            get { return tbDirAngle1.Text; }
        }

        public string ParabolaFocusDirectrixDistance
        {
            get { return tbP.Text; }
        }

        public string ParabolaFocusAngle
        {
            get { return tbDirAngle2.Text; }
        }

        public int DerivationFunctionOrder
        {
            get { return (int)nudJS.Value; }
        }

        public bool SaveRound
        {
            get { return cbSaveRound.Checked; }
        }

        public string XExpression
        {
            get { return tbX.Text; }
        }

        public string YExpression
        {
            get { return tbY.Text; }
        }

        public string ConstrainedVectorLength
        {
            get { return tbVecLen.Text; }
        }

        public string ConstrainedVectorDirectedAngle
        {
            get { return tbVecDirAngle.Text; }
        }

        void setBorder(Label destLabel)
        {
            List<Label> lbls = new List<Label> { lblRed, lblOrange, lblYellow, lblGreen, lblBlue, lblIngdigo, lblPurple, linkLabel1 };
            destLabel.BorderStyle = BorderStyle.FixedSingle;
            lbls.Remove(destLabel);
            foreach (Label item in lbls)
            {
                item.BorderStyle = BorderStyle.None;
            }
        }

        private void ToolsWindow_Load(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = true;
            lvTools.SetGroupState(ListViewGroupState.Collapsible);
        }
        private void lvTools_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvTools.SelectedItems.Count == 1)
            {
                Program.WinMain.ScaleButton.Checked = Program.WinMain.MoveObjectButton.Checked = 
                    Program.WinMain.MoveSketchPadButton.Checked = Program.WinMain.SwitchPointButton.Checked = false;
                Text = $"{Resources.Translate("ToolBox")} - {lvTools.SelectedItems[0].Text}";
                LinkedPad.SelectedToolType = (lvTools.SelectedItems[0] as ToolItem).ToolType;
                Program.WinMain.MainDockPanel.DockLeftPortion = (lvTools.SelectedItems[0] as ToolItem).WindowWidth;
                lvTools.ContextMenuStrip = cmsItem;
            }
            else
            {
                Text = $"{Resources.Translate("ToolBox")} - ({Resources.Translate("Selection")})";
                LinkedPad.SelectedToolType = ToolTypeName.zz;
                lvTools.ContextMenuStrip = cmsList;
            }
            switch (LinkedPad.SelectedToolType)
            {
                case ToolTypeName.zz:
                    splitContainer1.Panel2Collapsed = true;
                    tsbOK.Text = Resources.Translate("OK");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = false;
                    tscbOrder.Items.Clear();
                    break;
                case ToolTypeName.dxp:
                case ToolTypeName.qyxp:
                    tsbOK.Visible = false;
                    tsbReset.Visible = true;
                    plRubber.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.zcx:
                case ToolTypeName.zd:
                case ToolTypeName.zx:
                case ToolTypeName.sjxnx:
                case ToolTypeName.sjxwx:
                case ToolTypeName.sjxcx:
                case ToolTypeName.dbxzx:
                case ToolTypeName.wjy:
                case ToolTypeName.nqy:
                case ToolTypeName.ldjl:
                case ToolTypeName.ddzxdjl:
                case ToolTypeName.lzxjl:
                case ToolTypeName.lxldslj:
                case ToolTypeName.lxldxlj:
                case ToolTypeName.jpfx:
                case ToolTypeName.lzxjj:
                case ToolTypeName.sdjd:
                case ToolTypeName.jd:
                case ToolTypeName.qx:
                    tsbOK.Visible = true;
                    splitContainer1.Panel2Collapsed = tsbReset.Visible = false;
                    break;
                case ToolTypeName.lzxdj:
                    tsbOK.Visible = tsbReset.Visible = true;
                    plArrivalAngle.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yxysxd:
                    tsbOK.Visible = false;
                    tsbReset.Visible = true;
                    plConstrainedLineSegment.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.ysxl:
                    tsbOK.Visible = false;
                    tsbReset.Visible = true;
                    plConstrainedVector.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.zbd:
                    tsbOK.Visible = tsbReset.Visible = true;
                    plCoPoint.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.csfc:
                    tsbOK.Visible = tsbReset.Visible = true;
                    plCoPoint.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yxbjy:
                    label6.Text = $"{Resources.Translate("Radius")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = tsbOK.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.bjyxjsx:
                    label6.Text = $"{Resources.Translate("CentralAngle")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = tsbOK.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.xggx:
                    label6.Text = $"{Resources.Translate("Height")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = tsbOK.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.zdbx:
                    label6.Text = $"{Resources.Translate("EdgesNumber")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = tsbOK.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.tp:
                    label6.Text = $"{Resources.Translate("Address")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = tsbReset.Visible = true;
                    tbValue.Clear();
                    tsbOK.Visible = false;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.dhs:
                    tsbOK.Visible = tsbReset.Visible = true;
                    plDerivedFunction.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.ysty:
                    label12.Text = $"{Resources.Translate(nameof(EllipseBase.LongAxisHalfLength))}{Resources.ColonSeparate}";
                    label9.Text = $"{Resources.Translate(nameof(EllipseBase.ShortAxisHalfLength))}{Resources.ColonSeparate}";
                    tbA.Clear();
                    tbB.Clear();
                    tbDirAngle1.Text = "0";
                    tsbReset.Visible = true;
                    tsbOK.Visible = false;
                    plEllipseHyperbola.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yssqx:
                    label12.Text = $"{Resources.Translate(nameof(HyperbolaBase.RealAxisHalfLength))}{Resources.ColonSeparate}";
                    label9.Text = $"{Resources.Translate(nameof(HyperbolaBase.ImaginaryAxisHalfLength))}{Resources.ColonSeparate}";
                    tbA.Clear();
                    tbB.Clear();
                    tbDirAngle1.Text = "0";
                    tsbReset.Visible = true;
                    tsbOK.Visible = false;
                    plEllipseHyperbola.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yspwx:
                    tbDirAngle2.Text = "0";
                    tsbReset.Visible = true;
                    tsbOK.Visible = false;
                    plParabola.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yssx:
                    label6.Text = $"{Resources.Translate("DirectedAngle")}{Resources.ColonSeparate}";
                    tsbOK.Visible = btnBrowse.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.ysj:
                    label6.Text = $"{Resources.Translate("Angle")}{Resources.ColonSeparate}";
                    tsbOK.Visible = btnBrowse.Visible = false;
                    tbValue.Clear();
                    tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.jndfx:
                    label6.Text = $"{Resources.Translate("DivisionNumber")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = false;
                    tbValue.Clear();
                    tsbOK.Visible = tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.dbfd:
                    label6.Text = $"{Resources.Translate("Ratio")}{Resources.ColonSeparate}";
                    btnBrowse.Visible = false;
                    tbValue.Clear();
                    tsbOK.Visible = tsbReset.Visible = true;
                    plValue.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yszx:
                    tsbOK.Visible = false;
                    tsbReset.Visible = true;
                    plSlope.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.wb:
                    tsbOK.Visible = false;
                    tsbReset.Visible = true;
                    plText.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.yzb:
                    tsbOK.Visible = tsbReset.Visible = true;
                    tsbOK.Text = Resources.Translate("Submit");
                    selectedColor = Color.Red;
                    setBorder(lblRed);
                    plBrush.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.ygb:
                    tsbOK.Visible = tsbReset.Visible = true;
                    tsbOK.Text = Resources.Translate("Submit");
                    selectedColor = Color.Yellow;
                    setBorder(lblYellow);
                    plBrush.BringToFront();
                    splitContainer1.Panel2Collapsed = false;
                    break;
                case ToolTypeName.hs:
                    //sense = new frmIntellisense();
                    splitContainer1.Panel2Collapsed = true;
                    if (OpenFunctionInputWindow)
                    {
                        InputFunctionWindow funcinput = new InputFunctionWindow();
                        if (funcinput.ShowDialog() == DialogResult.OK)
                        {
                            RectangularCoordinate rc = LinkedPad.Coordinate as RectangularCoordinate;
                            if (rc != null && rc.XAxis.Unit.Value != Math.PI && InputFunctionWindow.ContainsTrigonometricFunction(funcinput.FunctionExpression))
                            {
                                DialogResult dr = MessageBox.Show(Resources.Translate("SwitchPIUnit"), Resources.Translate("Ask"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                if (dr == DialogResult.Yes)
                                {
                                    rc.XAxis.Unit.SetExpression("π");
                                    rc.XAxis.Scale.SetExpression(150);
                                }
                                else if (dr == DialogResult.Cancel)
                                {
                                    break;
                                }
                            }
                            LinkedPad.HostObj = new Function(LinkedPad,
                                $"{funcinput.FunctionName}({funcinput.IndependentVariable}) = {funcinput.FunctionExpression}",
                                ToolTypeName.hs, funcinput.FunctionExpression, funcinput.IndependentVariable);
                            LinkedPad.CreateAndCommand(LinkedPad.HostObj);
                        }
                    }
                    break;
                case ToolTypeName.zjsjx:
                case ToolTypeName.dyzjsjx:
                    tscbOrder.Items.Add($"{Resources.Translate("RightAngleEdge")}1 -> {Resources.Translate("RightAngleEdge")}2 -> ({Resources.Translate("Hypotenuse")})");
                    tscbOrder.Items.Add($"{Resources.Translate("RightAngleEdge")}1 -> {Resources.Translate("Hypotenuse")} -> ({Resources.Translate("RightAngleEdge")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hypotenuse")} -> {Resources.Translate("RightAngleEdge")}1 -> ({Resources.Translate("RightAngleEdge")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.dysjx:
                    tscbOrder.Items.Add($"{Resources.Translate("Isosceles")}1 -> {Resources.Translate("Isosceles")}2 -> ({Resources.Translate("Hemline")})");
                    tscbOrder.Items.Add($"{Resources.Translate("Isosceles")}1 -> {Resources.Translate("Hemline")} -> ({Resources.Translate("Isosceles")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hemline")} -> {Resources.Translate("Isosceles")}1 -> ({Resources.Translate("Isosceles")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.dytx:
                    tscbOrder.Items.Add($"{Resources.Translate("Waist")}1 -> {Resources.Translate("Hemline")}1 -> ({Resources.Translate("Waist")}2) -> ({Resources.Translate("Hemline")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hemline")}1 -> {Resources.Translate("Waist")}1 -> ({Resources.Translate("Hemline")}2) -> ({Resources.Translate("Waist")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.tx:
                    tscbOrder.Items.Add($"{Resources.Translate("Waist")}1 -> {Resources.Translate("Hemline")}1 -> {Resources.Translate("Waist")}2 -> ({Resources.Translate("Hemline")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hemline")}1 -> {Resources.Translate("Waist")}1 -> {Resources.Translate("Hemline")}2 -> ({Resources.Translate("Waist")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.zjtx:
                    tscbOrder.Items.Add($"{Resources.Translate("RightAngleWaist")} -> {Resources.Translate("Hemline")}1 -> {Resources.Translate("SlantingWaist")} -> ({Resources.Translate("Hemline")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hemline")}1 -> {Resources.Translate("RightAngleWaist")} -> {Resources.Translate("Hemline")}2 -> ({Resources.Translate("SlantingWaist")})");
                    tscbOrder.Items.Add($"{Resources.Translate("SlantingWaist")} -> {Resources.Translate("Hemline")}1 -> ({Resources.Translate("RightAngleWaist")}) -> ({Resources.Translate("Hemline")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Hemline")}1 -> {Resources.Translate("SlantingWaist")} -> ({Resources.Translate("Hemline")}2) -> ({Resources.Translate("RightAngleWaist")})");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.sxzsqx:
                    tscbOrder.Items.Add($"{Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> ({Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2 -> {Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> ({Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("RealAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2 -> ({Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.yxddy:
                    tscbOrder.Items.Add($"{Resources.Translate("CircleCenter")} -> {Resources.Translate("PointOnCircle")}");
                    tscbOrder.Items.Add($"{Resources.Translate("PointOnCircle")} -> {Resources.Translate("CircleCenter")}");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.cdzty:
                    tscbOrder.Items.Add($"{Resources.Translate("Vertex")}1 -> {Resources.Translate("Vertex")}2 -> {Resources.Translate("Vertex")}3 -> ({Resources.Translate("Vertex")}4)");
                    tscbOrder.Items.Add($"{Resources.Translate("Vertex")}1 -> {Resources.Translate("Vertex")}3 -> {Resources.Translate("Vertex")}2 -> ({Resources.Translate("Vertex")}4)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.jdddty:
                    tscbOrder.Items.Add($"{Resources.Translate("Focus")}1 -> {Resources.Translate("Focus")}2 -> {Resources.Translate("PointOnEllipse")}");
                    tscbOrder.Items.Add($"{Resources.Translate("PointOnEllipse")} -> {Resources.Translate("Focus")}1 -> {Resources.Translate("Focus")}2");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.jdddsqx:
                    tscbOrder.Items.Add($"{Resources.Translate("Focus")}1 -> {Resources.Translate("Focus")}2 -> {Resources.Translate("PointOnHyperbola")}");
                    tscbOrder.Items.Add($"{Resources.Translate("PointOnHyperbola")} -> {Resources.Translate("Focus")}1 -> {Resources.Translate("Focus")}2");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                case ToolTypeName.jdxzsqx:
                    tscbOrder.Items.Add($"{Resources.Translate("Focus")}1 -> {Resources.Translate("Focus")}2 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> ({Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2 -> {Resources.Translate("Focus")}1 -> ({Resources.Translate("Focus")}2)");
                    tscbOrder.Items.Add($"{Resources.Translate("Focus")}1 -> {Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}1 -> {Resources.Translate("Focus")}2 -> ({Resources.Translate("ImaginaryAxis")}{Resources.Join}{Resources.Translate("EndPoint")}2)");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
                //case ToolTypeName.jdzxty:
                //case ToolTypeName.jdzxsqx:
                //    tscbOrder.Items.Add($"焦点1 -> 焦点2 -> 准线");
                //    tscbOrder.Items.Add($"准线 -> 焦点1 -> 焦点2");
                //    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                //    SelectedPad.Canvas.Cursor = Cursors.Cross;
                //    break;
                case ToolTypeName.sdyh:
                case ToolTypeName.sdsx:
                case ToolTypeName.sdgx:
                    tscbOrder.Items.Add($"{Resources.Translate("EndPoint")}1 -> {Resources.Translate("PassPoint")} -> {Resources.Translate("EndPoint")}2");
                    tscbOrder.Items.Add($"{Resources.Translate("EndPoint")}1 -> {Resources.Translate("EndPoint")}2 -> {Resources.Translate("PassPoint")}");
                    toolStripLabel1.Enabled = tscbOrder.Enabled = true;
                    break;
            }
            if (!splitContainer1.Panel2Collapsed)
            {
                splitContainer1.SplitterDistance = splitContainer1.Height - toolStrip1.Height - (lvTools.SelectedItems[0] as ToolItem).OptionPanelHeight;
            }
            if (tscbOrder.Items.Count > 0)
            {
                tscbOrder.SelectedIndex = (lvTools.SelectedItems[0] as ToolItem).LastOrderIndex;
            }
        }
        private void tscbOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvTools.SelectedItems.Count == 1)
            {
                (lvTools.SelectedItems[0] as ToolItem).LastOrderIndex = tscbOrder.SelectedIndex;
            }
        }
        private void tsbOK_Click(object sender, EventArgs e)
        {
            LinkedPad.BuildOnce();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = $"{Resources.JoinLocalizedString("Image", "File")}(*.jpg;*.jpeg;*.bmp;*.png;*.gif;*.ico;*.emf;*.wmf)|*.jpg; *.jpeg; *.bmp; *.png; *.gif; *.ico; *.emf; *.wmf";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                tbValue.Text = ofd.FileName;
            }
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ColorDialog cd = new ColorDialog();
            if (cd.ShowDialog() == DialogResult.OK)
            {
                linkLabel1.LinkColor = selectedColor = cd.Color;
                setBorder(linkLabel1);
            }
        }
        void tsbView_ButtonClick(object sender, EventArgs e)
        {
            if (大图标ToolStripMenuItem.Checked)
            {
                小图标ToolStripMenuItem.Checked = true;
            }
            else
            {
                大图标ToolStripMenuItem.Checked = true;
            }
        }
        public void SketchPad_CoordinateChanged(SketchPad sender)
        {
            UIAdaptCoordinate();
        }
        void UIAdaptCoordinate()
        {
            int count = 0;
            string cpIK, peIK, co1, co2;
            if (LinkedPad.CoordinateType == CoordinateSystemType.PolarCoordinate)
            {
                cpIK = "zbd2";
                peIK = "csfc_jzb";
                co1 = "PolarRadius";
                co2 = "PolarAngle";
            }
            else
            {
                cpIK = "zbd";
                peIK = "csfc_zjzb";
                co1 = "Abscissa";
                co2 = "Ordinate";
            }
            foreach (ListViewItem item in lvTools.Items)
            {
                if (item.Text == Resources.Translate("CoordinatePoint"))
                {
                    item.ImageKey = cpIK;
                    count++;
                    if (count >= 2)
                    {
                        break;
                    }
                }
                else if (item.Text == Resources.Translate("ParametricEquation"))
                {
                    item.ImageKey = peIK;
                    count++;
                    if (count >= 2)
                    {
                        break;
                    }
                }
            }
            label1.Text = Resources.Translate(co1);
            label2.Text = Resources.Translate(co2);
        }
        private void lvTools_ItemActivate(object sender, EventArgs e)
        {
            LinkedPad.BuildOnce();
        }

        private void cbLength_CheckedChanged(object sender, EventArgs e)
        {
            tbLen.Enabled = cbLength.Checked;
            if (!cbLength.Checked && !cbAngle.Checked)
            {
                cbAngle.Checked = true;
            }
        }

        private void cbAngle_CheckedChanged(object sender, EventArgs e)
        {
            tbAngle.Enabled = cbAngle.Checked;
            if (!cbAngle.Checked && !cbLength.Checked)
            {
                cbLength.Checked = true;
            }
        }
        private void rbRegionEraser_CheckedChanged(object sender, EventArgs e)
        {
            if (rbRegionEraser.Checked)
            {
                LinkedPad.SelectedToolType = ToolTypeName.qyxp;
                foreach (ToolItem item in lvTools.Items)
                {
                    if (item.ToolType == ToolTypeName.dxp || item.ToolType == ToolTypeName.qyxp)
                    {
                        item.ToolType = ToolTypeName.qyxp;
                        break;
                    }
                }
            }
        }

        private void cbInfinity_CheckedChanged(object sender, EventArgs e)
        {
            tbSlope.Enabled = !cbInfinity.Checked;
        }

        private void tsbReset_Click(object sender, EventArgs e)
        {
            switch (LinkedPad.SelectedToolType)
            {
                case ToolTypeName.zbd:
                    tbX.Clear();
                    tbY.Clear();
                    break;
                case ToolTypeName.zdbx:
                case ToolTypeName.yxbjy:
                    tbValue.Clear();
                    break;
                case ToolTypeName.ysty:
                case ToolTypeName.yssqx:
                    tbA.Clear();
                    tbB.Clear();
                    tbDirAngle1.Text = "0";
                    break;
                case ToolTypeName.yspwx:
                    tbP.Clear();
                    tbDirAngle2.Text = "0";
                    break;
                case ToolTypeName.yxysxd:
                    tbLen.Clear();
                    tbAngle.Clear();
                    cbLength.Checked = cbAngle.Checked = true;
                    break;
                case ToolTypeName.ysxl:
                    tbVecLen.Clear();
                    tbVecDirAngle.Clear();
                    break;
                //case ToolTypeName.lzxjj:
                //    tbParaName.Clear();
                //    cbDirection.Checked = false;
                //    break;
                case ToolTypeName.wb:
                    tbText.Clear();
                    break;
                case ToolTypeName.yzb:
                    setBorder(lblRed);
                    break;
                case ToolTypeName.ygb:
                    setBorder(lblYellow);
                    break;
                case ToolTypeName.sz:
                    setBorder(lblBlue);
                    break;
                case ToolTypeName.dhs:
                    nudJS.Value = 1;
                    break;
                case ToolTypeName.lzxdj:
                    cbSaveRound.Checked = false;
                    break;
            }
        }

        private void ToolsWindow_SizeChanged(object sender, EventArgs e)
        {
            if (lvTools.SelectedItems.Count == 1)
            {
                (lvTools.SelectedItems[0] as ToolItem).WindowWidth = Program.WinMain.MainDockPanel.DockLeftPortion;
            }
        }

        bool changeIconMenuRaiseEvent = true;
        private void 大图标ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (!changeIconMenuRaiseEvent) return;
            if (大图标ToolStripMenuItem.Checked)
            {
                ChangeIconSize(true);
            }
            else
            {
                if (!小图标ToolStripMenuItem.Checked)
                {
                    changeIconMenuRaiseEvent = false;
                    大图标ToolStripMenuItem.Checked = true;
                    changeIconMenuRaiseEvent = true;
                }
            }
        }
        public void ChangeIconSize(bool large)
        {
            大图标ToolStripMenuItem.Checked = 大图标ToolStripMenuItem1.Checked = large;
            小图标ToolStripMenuItem.Checked = 小图标ToolStripMenuItem1.Checked = !large;
            lvTools.View = large ? View.LargeIcon : View.SmallIcon;
            refreshImageKey();
        }
        private void 小图标ToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
        {
            if (!changeIconMenuRaiseEvent) return;
            if (小图标ToolStripMenuItem.Checked)
            {
                ChangeIconSize(false);
            }
            else
            {
                if (!大图标ToolStripMenuItem.Checked)
                {
                    changeIconMenuRaiseEvent = false;
                    小图标ToolStripMenuItem.Checked = true;
                    changeIconMenuRaiseEvent = true;
                }
            }
        }
        void refreshImageKey()
        {
            foreach (ListViewItem item in lvTools.Items)
            {
                item.ImageKey = item.ImageKey;
            }
        }

        private void 大图标ToolStripMenuItem1_CheckedChanged(object sender, EventArgs e)
        {
            if (!changeIconMenuRaiseEvent) return;
            if (大图标ToolStripMenuItem1.Checked)
            {
                ChangeIconSize(true);
            }
            else
            {
                if (!小图标ToolStripMenuItem1.Checked)
                {
                    changeIconMenuRaiseEvent = false;
                    大图标ToolStripMenuItem1.Checked = true;
                    changeIconMenuRaiseEvent = true;
                }
            }
        }

        private void 小图标ToolStripMenuItem1_CheckedChanged(object sender, EventArgs e)
        {
            if (!changeIconMenuRaiseEvent) return;
            if (小图标ToolStripMenuItem1.Checked)
            {
                ChangeIconSize(false);
            }
            else
            {
                if (!大图标ToolStripMenuItem1.Checked)
                {
                    changeIconMenuRaiseEvent = false;
                    小图标ToolStripMenuItem1.Checked = true;
                    changeIconMenuRaiseEvent = true;
                }
            }
        }

        private void ToolsWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DockState = DockState.Hidden;
                e.Cancel = true;
            }
            Program.WinMain.ToolBoxMenu.Checked = false;
        }

        private void rbPointEraser_CheckedChanged(object sender, EventArgs e)
        {
            if (rbPointEraser.Checked)
            {
                LinkedPad.SelectedToolType = ToolTypeName.dxp;
                foreach (ToolItem item in lvTools.Items)
                {
                    if (item.ToolType == ToolTypeName.dxp || item.ToolType == ToolTypeName.qyxp)
                    {
                        item.ToolType = ToolTypeName.dxp;
                        break;
                    }
                }
            }
        }
        ToolTip angleTip = new ToolTip()
        {
            ToolTipTitle = Resources.Translate("Prompt"),
            ToolTipIcon =  ToolTipIcon.Info,
        };
        private void tbAngle_MouseHover(object sender, EventArgs e)
        {
            angleTip.Show(Resources.Translate("AngleInputTip"), tbAngle, 0, -40, 3000);
        }

        private void tbVecDirAngle_MouseHover(object sender, EventArgs e)
        {
            angleTip.Show(Resources.Translate("AngleInputTip"), tbAngle, 0, -40, 3000);
        }
    }
}
